import axios from 'axios'
import router from '@/router'
import { clearAll } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import { signToken } from '@/store'

const baseURL = process.env.VUE_APP_BASEURL
console.log(`axios baseUrl ==> ${baseURL}`)

const request = axios.create({
  baseURL,
  // withCredentials: true,
  timeout: 1000 * 60
})
// request interceptor
request.interceptors.request.use(
  config => {
    // const token = store.state.user.token
    config.headers['Authorization'] = signToken.value
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  ({ data }) => {
    const { code, msg } = data
    if (code !== undefined) {
      if (code !== 200) {
        if (code < 500)
          ElMessage.warning({
            message: msg || '服务异常',
            grouping: true
          })
        if (code >= 500)
          ElMessage.error({
            message: msg || '服务异常',
            grouping: true
          })
        if (code === 4001) {
          clearAll()
          ElMessage.error({
            message: '用户验证失败,请重新登录!',
            grouping: true
          })
          router.replace('/login')
        }
        // return Promise.reject(data)
      }
    }
    return data
  },
  error => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 2 * 1000,
      grouping: true
    })
    // return Promise.reject(error)
  }
)

export function httpGet(url, params, config = {}) {
  return request({
    url,
    method: 'get',
    params,
    ...config
  })
}

export function httpPost(url, data, config = {}) {
  return request({
    url,
    method: 'post',
    data,
    ...config
  })
}

export function httpPut(url, data, config = {}) {
  return request({
    url,
    method: 'put',
    data,
    ...config
  })
}
export function httpDel(url, data, config = {}) {
  return request({
    url,
    method: 'DELETE',
    data,
    ...config
  })
}
export async function uploadFile(file) {
  const formData = new FormData()
  formData.append('file', file.raw)
  return request({
    loading: true,
    url: '/smart/file/upload',
    method: 'post',
    data: formData
  })
}
// 导入题库
export function importSubject(data) {
  return request({
    isFormData: true,
    loading: true,
    url: '/question/importFromWord',
    method: 'post',
    data
  })
}

// 导出文件
export function httpExportExcel(url, params, config = {}) {
  return request({
    url,
    method: 'get',
    params,
    responseType: 'blob',
    ...config
  })
}

export default request
